//
//  PlayerViewController.m
//  MoeFM
//
//  Created by miyang on 14-11-7.
//  Copyright (c) 2014年 StraightJet. All rights reserved.
//



#import "PlayerViewController.h"
#import "Favs.h"

#import "ARTEmailSwipe.h"
#import "UIViewController+ARTEmailSwipe.h"

#import <MediaPlayer/MPNowPlayingInfoCenter.h>



static NSString *songURL;
@interface PlayerViewController ()

@property (nonatomic,assign)NSInteger sonIndex;
@property (nonatomic,strong)UILabel *pauseLabel;
@property (nonatomic,strong)NSUserDefaults *userDate;

@property (nonatomic,strong)MPNowPlayingInfoCenter *nowPlaying;

@end

@implementation PlayerViewController

+ (instancetype)sharPlayer
{
    static dispatch_once_t onceToken;
    static PlayerViewController *SharPlayer;
    
    dispatch_once(&onceToken, ^{
        SharPlayer = [[PlayerViewController alloc] init];
        
        
    });
    return SharPlayer;
    
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _sonIndex = 0;
        _netList = [[NSArray alloc] init];
        _localList = [[NSArray alloc] init];
        
        _nowplayingInfo = [[NSMutableDictionary alloc] init];
        _favID = 0;
        _pauseLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 120, 120)];
        _pauseLabel.backgroundColor = [UIColor colorWithRed:240/255.0f green:240/255.0f blue:240/255.0f alpha:.5];
        _audioPlayer = [[STKAudioPlayer alloc] init];
        [_audioPlayer setDelegate:self];
        self.view.layer.masksToBounds = YES;
        self.view.layer.borderWidth = .5;
        self.view.layer.borderColor = [[UIColor grayColor] CGColor];
        self.view.backgroundColor = [UIColor colorWithRed:240/255.0f green:240/255.0f blue:240/255.0f alpha:1];
        
        [[FavManager sharedManager] checkStatus];
        _nowPlaying = [MPNowPlayingInfoCenter defaultCenter];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UILabel *albumLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 35, 320, 60)];
    albumLabel.font = [UIFont systemFontOfSize:30];
    albumLabel.textAlignment = NSTextAlignmentCenter;
    albumLabel.text = @"专辑";
    self.albumLabel = albumLabel;
    
    
    UIImageView *coverIMG = [[UIImageView alloc] initWithFrame:CGRectMake(100, 105, 120, 120)];
    [coverIMG setImage:[UIImage imageNamed:@"back2.png"]];
    coverIMG.userInteractionEnabled = YES;
    coverIMG.layer.masksToBounds = YES;
    coverIMG.layer.cornerRadius = 60;
    UITapGestureRecognizer *playerController = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(playerControll)];
    [coverIMG addGestureRecognizer:playerController];
    self.coverIMG = coverIMG;
    
    UILabel *musicLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 250, 320, 50)];
        musicLabel.font = [UIFont systemFontOfSize:25];
    musicLabel.textAlignment = NSTextAlignmentCenter;
    musicLabel.text = @"曲名";
    self.musicLabel = musicLabel;
    
    UILabel *artistLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 310, 320, 40)];
    artistLabel.font = [UIFont systemFontOfSize:20];
    artistLabel.textAlignment = NSTextAlignmentCenter;
    artistLabel.text = @"艺术家";
    self.artistLabel = artistLabel;

    
    [self.view addSubview:albumLabel];
    [self.view addSubview:coverIMG];
    [self.view addSubview:musicLabel];
    [self.view addSubview:artistLabel];
    
    UIButton *heatBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    heatBtn.frame = CGRectMake(80, 370, 40, 40);
//    heatBtn.backgroundColor = [UIColor blueColor];
    [heatBtn setImage:[UIImage imageNamed:@"BlackHeart.png"] forState:UIControlStateNormal];
    heatBtn.tag = 0;
    [heatBtn addTarget:self action:@selector(collectionSet:) forControlEvents:UIControlEventTouchUpInside];
    self.heatBtn = heatBtn;
    
    UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    nextBtn.frame = CGRectMake(200, 370, 40, 40);
    //nextBtn.backgroundColor = [UIColor blueColor];
    [nextBtn setImage:[UIImage imageNamed:@"next.png"] forState:UIControlStateNormal];
    [nextBtn addTarget:self action:@selector(nextBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:nextBtn];
    [self.view addSubview:heatBtn];
    
    
}

- (void)playerControll
{
    if (_audioPlayer.state == STKAudioPlayerStatePlaying) {
        [_audioPlayer pause];
        
        [_nowplayingInfo setObject:@"0" forKey:MPNowPlayingInfoPropertyPlaybackRate];
    } else if (_audioPlayer.state == STKAudioPlayerStatePaused) {
        [_audioPlayer resume];
        
        [_nowplayingInfo setObject:@"1" forKey:MPNowPlayingInfoPropertyPlaybackRate];
    }
}

- (void)collectionSet:(UIButton *)btn
{
    if (_audioPlayer.state == STKAudioPlayerStatePlaying) {
        if ([FavManager sharedManager].status == UserStatusLogIn) {
            if (btn.tag == 0) {
                btn.tag = 1;
                [btn setImage:[UIImage imageNamed:@"RedHeart.png"] forState:UIControlStateNormal];
                [[FavManager sharedManager] favsAddWithType:@"song" andWikiID:_favID];
            } else if (btn.tag == 1){
                btn.tag = 0;
                [btn setImage:[UIImage imageNamed:@"BlackHeart.png"] forState:UIControlStateNormal];
                [[FavManager sharedManager] favsDelWithType:@"song" andWikiID:_favID];
            }
        }
    }
    
}

- (void)nextBtn
{
    if (_audioPlayer.state == STKAudioPlayerStatePlaying || _audioPlayer.state == STKAudioPlayerStatePaused) {
        
        if (_sonIndex == _netList.count-1) {
            NSLog(@"没有下一首了");
            
        } else {
            _sonIndex++;
            [self nextNetMusic];
        }
    }


}


- (void)playingWithURL:(NSString *)url andAlbumTitle:(NSString *)title
{
    
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    _sonIndex = 0;
    AFHTTPRequestOperationManager *playerList = [AFHTTPRequestOperationManager manager];
    [playerList GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [responseObject objectForKey:@"response"];
        _netList = [dic objectForKey:@"playlist"];
        _albumLabel.text = title;
        
        NSDictionary *dics = [_netList objectAtIndex:_sonIndex];
        NSDictionary *imgDic = [dics objectForKey:@"cover"];
        NSURL *imgurl = [NSURL URLWithString:[imgDic objectForKey:@"large"]];
        _musicLabel.text = [dics objectForKey:@"sub_title"];
        _artistLabel.text = [dics objectForKey:@"artist"];
        
        
        songURL = [dics objectForKey:@"url"];
//        [_coverIMG setImageWithURL:imgurl];
        __block double duration = _audioPlayer.duration;
        __block MPNowPlayingInfoCenter *nowInfo = _nowPlaying;
        __block UIImageView *cover = _coverIMG;
        [_coverIMG setImageWithURLRequest:[NSURLRequest requestWithURL:imgurl] placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
            [cover setImage:image];
            NSMutableDictionary *nowplayingInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                               [NSString stringWithFormat:@"%d",(int)duration],MPNowPlayingInfoPropertyElapsedPlaybackTime,
                               @"1",MPNowPlayingInfoPropertyPlaybackRate,
                               [dics objectForKey:@"sub_title"],MPMediaItemPropertyTitle,
                               [dics objectForKey:@"artist"],MPMediaItemPropertyArtist,nil];
            
            MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:image];
            [nowplayingInfo setObject:artwork forKey:MPMediaItemPropertyArtwork];
            nowInfo.nowPlayingInfo = nowplayingInfo;
        } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
            
        }];
        static dispatch_once_t start;
        dispatch_once(&start, ^{
            [self animation];
        });
        
        _heatBtn.tag = 0;
        NSString *subidstr = [dics objectForKey:@"sub_id"];
        NSInteger subid = [subidstr integerValue];
        _favID = subid;
        for (Sub *temp in [FavManager sharedManager].songarr) {
            if ([temp.sub_id integerValue] == subid) {
                _heatBtn.tag = 1;
                NSLog(@"yes");
                break;
            }
        }
        
        
        
        
        if (_heatBtn.tag == 1) {
            [_heatBtn setImage:[UIImage imageNamed:@"RedHeart.png"] forState:UIControlStateNormal];
        } else if (_heatBtn.tag == 0) {
            [_heatBtn setImage:[UIImage imageNamed:@"BlackHeart.png"] forState:UIControlStateNormal];
        } else {
            [_heatBtn setImage:[UIImage imageNamed:@"BlackHeart.png"] forState:UIControlStateNormal];
        }
        
        
        [_audioPlayer play:songURL];
     
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            _nowplayingInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys:
//                               [NSString stringWithFormat:@"%d",(int)_audioPlayer.duration],MPNowPlayingInfoPropertyElapsedPlaybackTime,
//                               @"1",MPNowPlayingInfoPropertyPlaybackRate,
//                               [dics objectForKey:@"sub_title"],MPMediaItemPropertyTitle,
//                               [dics objectForKey:@"artist"],MPMediaItemPropertyArtist,nil];
//            
//            MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:_coverIMG.image];
//            [_nowplayingInfo setObject:artwork forKey:MPMediaItemPropertyArtwork];
//              _nowPlaying.nowPlayingInfo = _nowplayingInfo;
//            
//    
//        });
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@ error",error);
    }];
}

- (void)nextNetMusic
{
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    NSLog(@"nextNetMusic");
    NSDictionary *dics = [_netList objectAtIndex:_sonIndex];
    NSDictionary *imgDic = [dics objectForKey:@"cover"];
    NSURL *imgurl = [NSURL URLWithString:[imgDic objectForKey:@"large"]];
    _musicLabel.text = [dics objectForKey:@"sub_title"];
    _artistLabel.text = [dics objectForKey:@"artist"];
    
    
    songURL = [dics objectForKey:@"url"];
//    [_coverIMG setImageWithURL:imgurl];
    
    __block double duration = _audioPlayer.duration;
    __block MPNowPlayingInfoCenter *nowInfo = _nowPlaying;
    __block UIImageView *cover = _coverIMG;
    [_coverIMG setImageWithURLRequest:[NSURLRequest requestWithURL:imgurl] placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
        [cover setImage:image];
        NSMutableDictionary *nowplayingInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                               [NSString stringWithFormat:@"%d",(int)duration],MPNowPlayingInfoPropertyElapsedPlaybackTime,
                                               @"1",MPNowPlayingInfoPropertyPlaybackRate,
                                               [dics objectForKey:@"sub_title"],MPMediaItemPropertyTitle,
                                               [dics objectForKey:@"artist"],MPMediaItemPropertyArtist,nil];
        
        MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:image];
        [nowplayingInfo setObject:artwork forKey:MPMediaItemPropertyArtwork];
        nowInfo.nowPlayingInfo = nowplayingInfo;
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
        
    }];
    
    
    
    
    NSString *subidstr = [dics objectForKey:@"sub_id"];
    NSInteger subid = [subidstr integerValue];
    _favID = subid;
    _heatBtn.tag = 0;
    for (Sub *temp in [FavManager sharedManager].songarr) {
        if ([temp.sub_id integerValue] == subid) {
            _heatBtn.tag = 1;
            NSLog(@"yes");
            break;
        }
    }
    
    if (_heatBtn.tag == 1) {
        [_heatBtn setImage:[UIImage imageNamed:@"RedHeart.png"] forState:UIControlStateNormal];
    } else if (_heatBtn.tag == 0) {
        [_heatBtn setImage:[UIImage imageNamed:@"BlackHeart.png"] forState:UIControlStateNormal];
    } else {
        [_heatBtn setImage:[UIImage imageNamed:@"BlackHeart.png"] forState:UIControlStateNormal];
    }
    [_audioPlayer play:songURL];
    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            _nowplayingInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys:
//                               [NSString stringWithFormat:@"%d",(int)_audioPlayer.duration],MPNowPlayingInfoPropertyElapsedPlaybackTime,
//                               @"1",MPNowPlayingInfoPropertyPlaybackRate,
//                               [dics objectForKey:@"sub_title"],MPMediaItemPropertyTitle,
//                               [dics objectForKey:@"artist"],MPMediaItemPropertyArtist,nil];
//        MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:_coverIMG.image];
//        [_nowplayingInfo setObject:artwork forKey:MPMediaItemPropertyArtwork];
//        
//        _nowPlaying.nowPlayingInfo = _nowplayingInfo;
//    });
    
}

//- (void)playingWithIpodItems:(NSArray *)mediaItemArray andIndex:(NSInteger)index
//{
//    if ([AFSoundManager sharedManager].status != AFSoundManagerStatusPlaying) {
//        [[AFSoundManager sharedManager] stop];
//    }
//    _heatBtn.tag = 2;
//    _sonIndex = index;
//    _localList = mediaItemArray;
//    MPMediaItem *item = [_localList objectAtIndex:_sonIndex];
//    _albumLabel.text = @"本地音乐";
//    _musicLabel.text = [item valueForProperty:MPMediaItemPropertyTitle];
//    _artistLabel.text = [item valueForProperty:MPMediaItemPropertyArtist];
//    if (_artistLabel.text == nil || [_artistLabel.text isEqualToString:@""]) {
//        _artistLabel.text = @"未知";
//    }
//    
//    NSURL *url = [item valueForProperty:MPMediaItemPropertyAssetURL];
//    
//    AVAudioPlayer *play = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
//    [play play];
//    
//    NSLog(@"%@",play.url) ;
//    
//}
//
//- (void)nextLocalMusic
//{
//    if ([AFSoundManager sharedManager].status == AFSoundManagerStatusPlaying) {
//        [[AFSoundManager sharedManager] stop];
//    }
//    _heatBtn.tag = 2;
//    MPMediaItem *item = [_localList objectAtIndex:_sonIndex];
//    _albumLabel.text = @"本地音乐";
//    _musicLabel.text = [item valueForProperty:MPMediaItemPropertyTitle];
//    _artistLabel.text = [item valueForProperty:MPMediaItemPropertyArtist];
//    [[AFSoundManager sharedManager] startPlayingIpodFileWithMPMediaItem:item andBlock:^(int percentage, CGFloat elapsedTime, CGFloat timeRemaining, NSError *error, BOOL finished) {
//        NSLog(@"%d",percentage);
//    }];
//}

- (void)animation
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    animation.toValue = [NSNumber numberWithFloat:M_PI * 2.0];
    [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [animation setDuration:15];
    [animation setRepeatCount:100000];
    [animation setCumulative:NO];
    [animation setRemovedOnCompletion:NO];
    [animation setFillMode:kCAFillModeForwards];
    [_coverIMG.layer addAnimation:animation forKey:@"Rotation"];
    
}



//用来暂停layer上的动画
-(void)pauseLayer:(CALayer*)layer
{
    CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
    layer.speed = 0.0;
    layer.timeOffset = pausedTime;
}
//恢复layer上的动画
-(void)resumeLayer:(CALayer*)layer
{
    CFTimeInterval pausedTime = [layer timeOffset];
    layer.speed = 1.0;
    layer.timeOffset = 0.0;
    layer.beginTime = 0.0;
    CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    layer.beginTime = timeSincePause;
}



- (void)request:(NSString *)path andParameters:(NSDictionary *)parameters
{
    
    NSURLRequest *request = [OAuth1Controller preparedRequestForPath:path
                                                          parameters:parameters
                                                          HTTPmethod:@"GET"
                                                          oauthToken:self.oauthToken
                                                         oauthSecret:self.oauthTokenSecret];
    AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    op.responseSerializer = [AFJSONResponseSerializer serializer];
    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *returndic = [responseObject valueForKey:@"response"];
        NSArray *favs = [returndic objectForKey:@"favs"];
        
        NSMutableArray *radioarr = [[NSMutableArray alloc] init];
        NSMutableArray *musicarr = [[NSMutableArray alloc] init];
        
        
        for (NSDictionary *favdic in favs) {
            Favs *favobj = [[Favs alloc] init];
            NSDictionary *obj = [favdic objectForKey:@"obj"];
            favobj.wiki_name = [obj objectForKey:@"wiki_name"];
            favobj.wiki_title = [obj objectForKey:@"wiki_title"];
            favobj.wiki_meta = [obj objectForKey:@"wiki_meta"];
            favobj.wiki_cover = [obj objectForKey:@"wiki_cover"];
            favobj.wiki_id = [obj objectForKey:@"wiki_id"];
            if ([[favdic valueForKey:@"fav_obj_type"] isEqualToString:@"radio"]) {
                [radioarr addObject:favobj];
            } else if ([[favdic valueForKey:@"fav_obj_type"] isEqualToString:@"music"]) {
                [musicarr addObject:favobj];
            }
        }
        _radioarr = radioarr;
        _musicarr = musicarr;
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
    
    
    [[NSOperationQueue mainQueue] addOperation:op];
}

- (void)favSet:(NSString *)path andParameters:(NSDictionary *)parameters
{
    
    NSURLRequest *request = [OAuth1Controller preparedRequestForPath:path
                                                          parameters:parameters
                                                          HTTPmethod:@"GET"
                                                          oauthToken:self.oauthToken
                                                         oauthSecret:self.oauthTokenSecret];
    AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    op.responseSerializer = [AFJSONResponseSerializer serializer];
    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"set fav");
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
    
    
    [[NSOperationQueue mainQueue] addOperation:op];
}

/// Raised when an item has started playing
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didStartPlayingQueueItemId:(NSObject*)queueItemId
{
    NSLog(@"start playing");
}
/// Raised when an item has finished buffering (may or may not be the currently playing item)
/// This event may be raised multiple times for the same item if seek is invoked on the player
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject*)queueItemId
{
    
}
/// Raised when the state of the player has changed
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousState
{
    NSLog(@"state changed %d      previousState %d",state,previousState);
    if (state == 16) {
        [self resumeLayer:_coverIMG.layer];
        [_pauseLabel removeFromSuperview];
    } else if (state == 3) {
        [self resumeLayer:_coverIMG.layer];
        [_pauseLabel removeFromSuperview];
    } else if (state == 5) {
        [self pauseLayer:_coverIMG.layer];
        [_coverIMG addSubview:_pauseLabel];
    } else if (state == 9) {
        [self pauseLayer:_coverIMG.layer];
        [_coverIMG addSubview:_pauseLabel];
    }
}


/// Raised when an item has finished playing
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishPlayingQueueItemId:(NSObject*)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration
{
    NSLog(@"finish playing");
    NSLog(@"stopreason%d",stopReason);
    if (stopReason == 0) {
        return;
    } else if (stopReason == 2) {
        return;
    } else {
        if (_sonIndex == _netList.count-1) {
            NSLog(@"没有下一首了");
            
        } else {
            _sonIndex++;
            [self nextNetMusic];
        }
    }

}



/// Raised when an unexpected and possibly unrecoverable error has occured (usually best to recreate the STKAudioPlauyer)
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer unexpectedError:(STKAudioPlayerErrorCode)errorCode
{
    
}

/// Optionally implemented to get logging information from the STKAudioPlayer (used internally for debugging)
//获取STKaudioplayer的日志信息
//-(void) audioPlayer:(STKAudioPlayer*)audioPlayer logInfo:(NSString*)line
//{
//    
//}
/// Raised when items queued items are cleared (usually because of a call to play, setDataSource or stop)
//-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didCancelQueuedItems:(NSArray*)queuedItems
//{
//    
//}

@end
